package study.eggs.utils;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.soap.MimeHeaders;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.util.Objects;

@Slf4j
public class WebUtils {

    private static final String DEFAULT_CONTENT_TYPE = "application/fastjson; charset=UTF-8";

    /**
     * 转HttpServletRequest
     *
     * @param request -ServletRequest
     */
    public HttpServletRequest toHttp(ServletRequest request) {
        return (HttpServletRequest) request;
    }

    /**
     * 转HttpServletResponse
     *
     * @param response -ServletResponse
     */
    public HttpServletResponse toHttp(ServletResponse response) {
        return (HttpServletResponse) response;
    }

    /**
     * 获取请求头
     *
     * @param request -HttpServletRequest
     * @param name    -String
     */
    public static String getHeader(HttpServletRequest request, String name) {
        return request.getHeader(name);
    }

    /**
     * 修改请求头
     *
     * @param request -HttpServletRequest
     * @param name    -String
     */
    public static void addHeader(HttpServletRequest request, String name, String value) {
        //
        Class<?> clazz = request.getClass();
        log.info("{}", clazz.getName());
        try {
            //request
            Field f1 = clazz.getDeclaredField("request");
            f1.setAccessible(true);
            Object reqObj = f1.get(request);
            //coyoteRequest
            Field f2 = reqObj.getClass().getDeclaredField("coyoteRequest");
            f2.setAccessible(true);
            Object coyoteObj = f2.get(reqObj);
            //System.out.println("coyoteRequest实现类="+o1.getClass().getName());
            //headers
            Field f3 = coyoteObj.getClass().getDeclaredField("headers");
            f3.setAccessible(true);
            MimeHeaders headers = (MimeHeaders) f3.get(coyoteObj);
//            headers.addValue(name)
//                    .setString(value);
        } catch (Exception ex) {
            throw new RuntimeException("", ex);
        }
    }

    /**
     * 获取Cookie值
     *
     * @param request -HttpServletRequest
     * @param name    -String
     */
    public static String getCookie(HttpServletRequest request, String name) {
        Cookie[] cookies = request.getCookies();
        String value = null;
        for (Cookie cookie : cookies) {
            if (Objects.equals(cookie.getName().toLowerCase(), name.toLowerCase())) {
                value = cookie.getValue();
            }
        }
        return value;
    }

    /**
     * 输出响应
     *
     * @param response   -HttpServletResponse
     * @param statusCode -int
     */
    public static void write(HttpServletResponse response, int statusCode) {
        write(response, statusCode, null);
    }

    /**
     * @param response -HttpServletResponse
     * @param result   -Result
     */
    public static void write(HttpServletResponse response, Object result) {
        write(response, HttpServletResponse.SC_OK, result);
    }

    /**
     * @param response   -HttpServletResponse
     * @param statusCode -int
     * @param result     -Result
     */
    public static void write(HttpServletResponse response, int statusCode, Object result) {
        PrintWriter writer = null;
        try {
            //
            response.setContentType(DEFAULT_CONTENT_TYPE);
            response.setStatus(statusCode);
            //
            if (result != null) {
                writer = response.getWriter();
                String text = JsonUtils.toJson(result);
                writer.write(text);
            }
        } catch (Exception ex) {
            log.error("", ex);
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }

    /**
     * 发送错误
     *
     * @param response   -HttpServletRequest
     * @param statusCode -int
     */
    public static void sendError(HttpServletResponse response, int statusCode) {
        sendError(response, statusCode, null);
    }

    /**
     * @param response   -HttpServletRequest
     * @param statusCode -int
     * @param msg        -String
     */
    public static void sendError(HttpServletResponse response, int statusCode, String msg) {
        try {
            response.sendError(statusCode, msg);
        } catch (Exception ex) {
            log.error("", ex);
        }
    }

    /**
     * 是否是上传请求
     *
     * @param request -HttpServletRequest
     */
    public static boolean isMultipart(HttpServletRequest request) {
        String contentType = request.getContentType();
        return contentType != null && contentType.startsWith("multipart/");
    }
}
